package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {


    @Autowired
    private TokenService tokenService;

    // 处理Controller层请求前拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //失败校验1:校验携带的token是否为空
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED); //设置状态码401
            return false;
        }
        //失败校验2:校验解析token是否为空
        Claims claims = tokenService.parseToken(token);
        if (ObjectUtil.isNull(claims)) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }
        //失败校验3:校验解析token的userId是否为空
        Object userId = claims.get("userId");
        if (ObjectUtil.isNull(userId)) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }

        //校验成功后将用户的信息进行存储
        UserThreadLocal.setValue(Long.valueOf(userId.toString()));
        return true;
    }

    // 处理Controller层请求后拦截
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.clean();
    }
}
